1890F - Game of Stacks - CodeForces Solution


dfs and similar graphs implementation trees

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define maxx 100001

vector<int> ret(maxx),visited(maxx),stk(maxx),dfstk(maxx*10),v[maxx];
int tt;

int rt(int x)
{
    if(stk[x]==(-1))
    {
        return 1;
    }

    return 0;
}

int dfs(int cur)
{
    if(ret[cur]!=0)
    {
        return ret[cur];
    }
    if(rt(cur)==1)
    {
        return cur;
    }
    if(visited[cur]!=0)
    {
        dfstk[tt]=0;
        while(dfstk[tt]!=cur)
        {
            stk[dfstk[tt-1]]=stk[dfstk[tt-1]]-1;
            visited[dfstk[tt-1]]=0;
            tt=tt-1;
        }
        return dfs(cur);
    }
    else
    {
        visited[cur]=1;
    }
    int to=v[cur][stk[cur]];
    dfstk[tt]=cur;
    tt=tt+1;

    return dfs(to);
}

void nw(int x)
{
    while(tt!=0)
    {
        ret[dfstk[tt-1]]=x;
        tt=tt-1;
    }
}

main()
{
    int k,n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int k;
        scanf("%d",&k);
        stk[i]=k-1;
        for(int j=0;j<k;j++)
        {
            int x;
            scanf("%d",&x);
            v[i].push_back(x);
        }
    }
    for(int i=1;i<=n;i++)
    {
        int st=dfs(i);
        printf("%d%s",st,(i==n?"\n":" "));
        nw(st);
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

244A - Dividing Orange
1061C - Multiplicity
1312A - Two Regular Polygons
801A - Vicious Keyboard
510B - Fox And Two Dots
616D - Longest k-Good Segment
1604A - Era
555B - Case of Fugitive
551A - GukiZ and Contest
1399F - Yet Another Segments Subset
1371C - A Cookie for You
430B - Balls Game
1263A - Sweet Problem
1332B - Composite Coloring
254A - Cards with Numbers
215A - Bicycle Chain
1288B - Yet Another Meme Problem
1201C - Maximum Median
435A - Queue on Bus Stop
1409B - Minimum Product
723B - Text Document Analysis
1471C - Strange Birthday Party
1199A - City Day
1334A - Level Statistics
67B - Restoration of the Permutation
1734A - Select Three Sticks
1734B - Bright Nice Brilliant
357B - Flag Day
937A - Olympiad
1075A - The King's Race